package com.yixun.qfbao.api.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.google.gson.JsonObject;
import com.yixun.qfbao.api.service.HomeService;
import com.yixun.qfbao.mapper.*;
import com.yixun.qfbao.model.*;
import com.yixun.qfbao.model.dto.CompanyDto;
import com.yixun.qfbao.model.dto.LogoDto;
import com.yixun.qfbao.model.dto.SubscriptionDto;
import com.yixun.qfbao.model.dto.WxBindDto;
import com.yixun.qfbao.model.enums.DelFlagEnum;
import com.yixun.qfbao.model.enums.LogoTypeEnum;
import com.yixun.qfbao.model.enums.SystemIdEnum;
import com.yixun.qfbao.util.WeixinCommon;
import com.yixun.qfbao.xf.model.AttetionInfo;
import com.yixun.qfbao.xf.model.enums.AttetionStatusEnum;
import com.yixun.qfbao.xf.model.enums.ResultEnum;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * 分销小程序首页接口
 * @author zilong.liu
 *
 */
@Service
@Slf4j
public class HomeServiceImpl implements HomeService{
	
	@Autowired
	WeixinCommon weixinCommon;
	@Autowired
	CompanyMapper companyMapper;
	@Autowired
	WxBindMapper wxBindMapper;
	@Autowired
	PartnerInfoMapper partnerInfoMapper;
	@Autowired
	SubscriptionMapper subscriptionMapper;
	@Autowired
	LogoMapper logoMapper;

	/**
	 * 首页，获取关注信息
	 */
	@Override
	public AttetionInfo getAttetionInfo(String systemId, String partnerId, String companyUuid) {
		log.info("首页，获取关注信息  getAttetionInfo  request systemId:{} partnerId:{} companyUuid:{}",systemId,partnerId,companyUuid);
		AttetionInfo attetionInfo = new AttetionInfo();
		attetionInfo.setResCode(ResultEnum.SUCCESS.getNo());
		if(StringUtils.isEmpty(partnerId)) {
			attetionInfo.setResCode(ResultEnum.FAIL.getNo());
			attetionInfo.setResMsg("传入partnerId信息为空");
			return attetionInfo;
		}
		if(StringUtils.isEmpty(companyUuid)) {
			attetionInfo.setResCode(ResultEnum.FAIL.getNo());
			attetionInfo.setResMsg("传入companyUuid信息为空");
			return attetionInfo;
		}
		if(StringUtils.isEmpty(systemId)) {
			attetionInfo.setResCode(ResultEnum.FAIL.getNo());
			attetionInfo.setResMsg("传入systemId信息为空");
			return attetionInfo;
		}
		CompanyDto companyDto = new CompanyDto();
		companyDto.setCompanyUuid(companyUuid);
		Company company = companyMapper.selectByDto(companyDto);
		if(company == null) {
			attetionInfo.setResCode(ResultEnum.FAIL.getNo());
			attetionInfo.setResMsg("传入companyUuid有误");
			return attetionInfo;
		}
		String enableWeappMsg = company.getEnableWeappMsg();
		if(!"1".equals(enableWeappMsg)) {
//			systemId = SystemIdEnum.AGENCY_h5.getCode();
			attetionInfo.setResCode(ResultEnum.FAIL.getNo());
			attetionInfo.setResMsg("未开启分销小程序消息推送配置");
			return attetionInfo;
		}
		// 获取关注状态
		if(SystemIdEnum.WEAPP_AGENCY.getCode().equals(systemId)) {
			getAttetionStatus(SystemIdEnum.WEAPP_AGENCY_WX_ACCOUNTS.getCode(), 
					partnerId, companyUuid, attetionInfo);
		}
		// 未关注，则获取提示信息,，登录渠道必定是分销小程序
		if(AttetionStatusEnum.cancel_attetion.getCode().toString().equals(attetionInfo.getAttetionStatus())) {
			getAttetionInfo(company.getId(), companyUuid, systemId, attetionInfo);
		}
		log.info("getAttetionInfo  response {}",JSONObject.toJSONString(attetionInfo));
		return attetionInfo;
	}
	
	/**
	 * 获取当前人的关注状态
	 * 	根据当前的wxopenId，判断tm_wx_bind表中是否存在对应的关注数据。
	 * 	要根据是否开启小程序消息推送判断关注的对应appId
	 * @param systemId
	 * @param partnerId
	 * @param companyUuid
	 * @param attetionInfo
	 */
	private void getAttetionStatus(String systemId, String partnerId, String companyUuid, AttetionInfo attetionInfo) {
		log.info("获取当前人的关注状态  getAttetionStatus  request systemId:{} partnerId:{} companyUuid:{} attetionInfo:{}",systemId,partnerId,companyUuid, JSONObject.toJSONString(attetionInfo));
		String appId = weixinCommon.getRealAppId(systemId, companyUuid);
		PartnerInfo partnerInfo = partnerInfoMapper.selectById(Long.parseLong(partnerId));
		if (partnerInfo == null) {
			attetionInfo.setResCode(ResultEnum.FAIL.getNo());
			attetionInfo.setResMsg("传入companyUuid有误");
			return;
		}
		String openId = partnerInfo.getWxOpenid();
		// 没有openId， 则未关注，需要重新关注
		if (StringUtils.isEmpty(openId)) {
			log.info("没有openId， 则未关注，需要重新关注 AttetionStatus：{} ",AttetionStatusEnum.cancel_attetion.getDes());
			attetionInfo.setAttetionStatus(AttetionStatusEnum.cancel_attetion.getCode().toString());
			return;
		}
		WxBindDto wxBindDto = new WxBindDto();
		wxBindDto.setAppId(appId);
		wxBindDto.setWxOpenId(openId);
		wxBindDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
		wxBindDto.setAttentionStatus(AttetionStatusEnum.set_attetion.getCode().toString());
		WxBind wxBind = wxBindMapper.selectByDto(wxBindDto);
		log.info("wxBind result {}",JSONObject.toJSONString(wxBind));
		if(wxBind == null) {
			log.info("wxBind为空 取消关注 AttetionStatus：{} ",AttetionStatusEnum.cancel_attetion.getDes());
			attetionInfo.setAttetionStatus(AttetionStatusEnum.cancel_attetion.getCode().toString());
			return;
		}
		log.info("wxBind不为空 关注 AttetionStatus：{} ",AttetionStatusEnum.set_attetion.getDes());
		attetionInfo.setAttetionStatus(AttetionStatusEnum.set_attetion.getCode().toString());
	}
	
	/**
	 * 获取关注信息
	 */
	private void getAttetionInfo(long companyId, String companyUuid, String systemId, AttetionInfo attetionInfo) {
		systemId = convertSystemId(systemId);
		SubscriptionDto subscriptionDto = new SubscriptionDto();
		subscriptionDto.setCompanyUuid(companyUuid);
		subscriptionDto.setSystemId(systemId);
		subscriptionDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
		Subscription subscription = subscriptionMapper.selectByDto(subscriptionDto);
		String appName = subscription.getAppName();
		LogoDto logoDto = new LogoDto();
		logoDto.setLogoType(LogoTypeEnum.TYPE_9.getNo());
		logoDto.setLogoMerchantid(companyId);
		logoDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
		Logo logo = logoMapper.selectByDto(logoDto);
		if(logo != null) {
			String logoUrl = logo.getLogoUrl();
			attetionInfo.setAgencyServiceLogoUrl(logoUrl);
		}
		attetionInfo.setAgencyServiceName(appName);
	}
	
	private static final Map<String, String> SYSTEM_REL_MAP = new HashMap<>();
	
	static {
		SYSTEM_REL_MAP.put(SystemIdEnum.WEAPP_AGENCY.getCode(), SystemIdEnum.WEAPP_AGENCY_WX_ACCOUNTS.getCode());
	}
	
	private String convertSystemId(String systemId) {
		if(StringUtils.isNotEmpty(SYSTEM_REL_MAP.get(systemId))) {
			return SYSTEM_REL_MAP.get(systemId);
		}
		return systemId;
	}
}
